//
//  MarketDetailViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 6/4/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "MarketDetailViewController.h"
#import "BidTableViewCell.h"
#import "OfferTableViewCell.h"
#import "TraceTableViewCell.h"

@interface MarketDetailViewController () <UITableViewDataSource, UITableViewDelegate>
{
    UITableView *bidTableView;
    UITableView *offerTableView;
    UITableView *traceTableView;
    NSDictionary *bondInfo;
    
    NSArray *offerArray;
    NSArray *bidArray;
    NSArray *traceArray;
}

@end

@implementation MarketDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [MBProgressHUD showHUDAddedTo:bidTableView animated:YES].dimBackground = YES;
    [MBProgressHUD showHUDAddedTo:offerTableView animated:YES].dimBackground = YES;
    NSString *cusip = [[Shared shared].bondInfo objectForKey:@"cusip"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    [manager GET:[NSString stringWithFormat:@"%@%@", BIDASKDETAILURL, cusip] parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
        
        [MBProgressHUD hideHUDForView:bidTableView animated:YES];
        [MBProgressHUD hideHUDForView:offerTableView animated:YES];
        NSDictionary *data = [JSON objectForKey:@"data"];
        offerArray = [data objectForKey:@"offersList"];
        DDLogVerbose(@"Offer Array:\n%@", offerArray);
        bidArray = [data objectForKey:@"bidsList"];
        DDLogVerbose(@"Bid Array:\n%@", bidArray);
        [bidTableView reloadData];
        [offerTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogError(@"Get bid offer array error:\n%@", error);
        [MBProgressHUD hideHUDForView:bidTableView animated:YES];
        [MBProgressHUD hideHUDForView:offerTableView animated:YES];
    }];
    
    [MBProgressHUD showHUDAddedTo:traceTableView animated:YES].dimBackground = YES;
    NSDictionary *params = @{@"marketSectorDes": [[Shared shared].bondInfo objectForKey:@"marketSectorDes"]};
    [manager POST:[NSString stringWithFormat:@"%@%@", TRACEDETAILURL, cusip] parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:traceTableView animated:YES];
        
        NSDictionary *dictionary = [responseObject objectForKey:@"data"];
        traceArray = [dictionary objectForKey:@"traceList"];
        DDLogVerbose(@"Trace Array:\n%@", traceArray);
        [traceTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:traceTableView animated:YES];
        DDLogError(@"Get Trace array error:\n%@", error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = [[Shared shared].bondInfo objectForKey:@"description"];
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonPressed:)];
    settingBarButton.tintColor = SUMRIDGECOLOR;
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonPressed:)];
    backBarButton.tintColor = SUMRIDGECOLOR;
    NSArray *leftItems = @[settingBarButton, backBarButton];
    self.navigationItem.leftBarButtonItems = leftItems;
    
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // remove scroll view top white space
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    
    bidTableView = [[UITableView alloc] init];
    bidTableView.tag = 1;
    bidTableView.dataSource = self;
    bidTableView.delegate = self;
    bidTableView.showsVerticalScrollIndicator = NO;
    bidTableView.separatorInset = UIEdgeInsetsZero;
    bidTableView.layoutMargins = UIEdgeInsetsZero;
    [bidTableView setTableFooterView:view];
    [self.view addSubview:bidTableView];
    
    offerTableView = [[UITableView alloc] init];
    offerTableView.tag = 2;
    offerTableView.dataSource = self;
    offerTableView.delegate = self;
    offerTableView.showsVerticalScrollIndicator = NO;
    offerTableView.separatorInset = UIEdgeInsetsZero;
    offerTableView.layoutMargins = UIEdgeInsetsZero;
    [offerTableView setTableFooterView:view];
    [self.view addSubview:offerTableView];
    
    traceTableView = [[UITableView alloc] init];
    traceTableView.tag = 3;
    traceTableView.dataSource = self;
    traceTableView.delegate = self;
    traceTableView.showsVerticalScrollIndicator = NO;
    traceTableView.separatorInset = UIEdgeInsetsZero;
    traceTableView.layoutMargins = UIEdgeInsetsZero;
    [traceTableView setTableFooterView:view];
    [self.view addSubview:traceTableView];
    
    if ([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight ||
        [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft) {
        [bidTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.left.equalTo(self.view).offset(5);
            make.width.mas_equalTo((self.view.frame.size.width/2 - 20)/2);
            make.bottom.equalTo(self.view).offset(-5);
        }];
        
        [offerTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.left.equalTo(bidTableView.mas_right).offset(10);
            make.width.mas_equalTo((self.view.frame.size.width/2 - 20)/2);
            make.bottom.equalTo(self.view).offset(-5);
        }];
        
        [traceTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.right.equalTo(self.view).offset(-5);
            make.width.mas_equalTo(self.view.frame.size.width/2 - 20);
            make.bottom.equalTo(self.view).offset(-5);
        }];
    } else {
        [bidTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(69);
            make.left.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width/2 - 2.5, 200));
        }];
        
        [offerTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(69);
            make.right.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width/2 - 2.5, 200));
        }];
        
        [traceTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(offerTableView.mas_bottom).offset(5);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
    }
    
    UISwipeGestureRecognizer *swipeGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backBarButtonPressed:)];
    swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeGestureRight];
}

- (void)settingBarButtonPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)backBarButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Setting Rotate

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIDeviceOrientationLandscapeRight ||
        toInterfaceOrientation == UIDeviceOrientationLandscapeLeft) {
        [traceTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.right.equalTo(self.view).offset(-5);
            make.width.mas_equalTo(280);
            make.bottom.equalTo(self.view).offset(-5);
        }];
        
        [offerTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.right.equalTo(traceTableView.mas_left).offset(-5);
            make.width.mas_equalTo((self.view.frame.size.width - 295)/2);
            make.bottom.equalTo(self.view).offset(-5);
        }];
        
        [bidTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(46);
            make.right.equalTo(offerTableView.mas_left).offset(-5);
            make.width.mas_equalTo((self.view.frame.size.width - 295)/2);
            make.bottom.equalTo(self.view).offset(-5);
        }];
    } else {
        [bidTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(69);
            make.left.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width/2 - 2.5, 200));
        }];
        
        [offerTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(69);
            make.right.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width/2 - 2.5, 200));
        }];
        
        [traceTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(offerTableView.mas_bottom).offset(5);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
    }
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (tableView.tag == 1) {
        return [bidArray count];
    } else if (tableView.tag == 2) {
        return [offerArray count];
    } else {
        return [traceArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1) {
        BidTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Bid"];
        
        // Configure the cell...
        if (cell == nil) {
            cell = [[BidTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Bid"];
            cell.separatorInset = UIEdgeInsetsZero;
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        
        if ([bidArray count] != 0 &&
            [indexPath row] < [bidArray count]) {
            [cell setUIFrame];
            [cell setLabelText:[bidArray objectAtIndex:indexPath.row]];
        }
        
        return cell;
    } else if (tableView.tag == 2) {
        OfferTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Offer"];
        
        // Configure the cell...
        if (cell == nil) {
            cell = [[OfferTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Offer"];
            cell.separatorInset = UIEdgeInsetsZero;
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        
        if ([offerArray count] != 0 &&
            [indexPath row] < [offerArray count]) {
            [cell setUIFrame];
            [cell setLabelText:[offerArray objectAtIndex:indexPath.row]];
        }
        
        return cell;
    } else {
        TraceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Trace"];
        
        // Configure the cell...
        if (cell == nil) {
            cell = [[TraceTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Trace"];
            cell.separatorInset = UIEdgeInsetsZero;
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        
        if ([traceArray count] != 0 &&
            [indexPath row] < [traceArray count]) {
            [cell setUIFrame];
            [cell setLabelText:[traceArray objectAtIndex:[indexPath row]]];
        }
        
        return cell;
    }
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 24.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 1) {
        return 24.0;
    } else {
        return 24.0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 230.0, 24.0)];
        [view setBackgroundColor:SUMRIDGECOLOR];
        UILabel *label1 = [[UILabel alloc] init];
        label1.textColor = [UIColor whiteColor];
        label1.font = ARIAL10;
        label1.text = @"BID";
        [view addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc] init];
        label2.textAlignment = NSTextAlignmentRight;
        label2.textColor = [UIColor whiteColor];
        label2.font = ARIAL10;
        label2.text = @"YTW";
        [view addSubview:label2];
        
        UILabel *label3 = [[UILabel alloc] init];
        label3.textAlignment = NSTextAlignmentRight;
        label3.textColor = [UIColor whiteColor];
        label3.font = ARIAL10;
        label3.text = @"Spread";
        [view addSubview:label3];
        
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(60);
        }];
        
        [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).offset(-5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(40);
        }];
        
        [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(label3.mas_left).offset(-5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(30);
        }];
        
        
        
        return view;
    }
    else if (tableView.tag == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 230.0, 24.0)];
        [view setBackgroundColor:SUMRIDGECOLOR];
        UILabel *label1 = [[UILabel alloc] init];
        label1.textColor = [UIColor whiteColor];
        label1.font = ARIAL10;
        label1.text = @"OFFER";
        [view addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc] init];
        label2.textAlignment = NSTextAlignmentRight;
        label2.textColor = [UIColor whiteColor];
        label2.font = ARIAL10;
        label2.text = @"YTW";
        [view addSubview:label2];
        
        UILabel *label3 = [[UILabel alloc] init];
        label3.textAlignment = NSTextAlignmentRight;
        label3.textColor = [UIColor whiteColor];
        label3.font = ARIAL10;
        label3.text = @"Spread";
        [view addSubview:label3];
        
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(60);
        }];
        
        [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).offset(-5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(40);
        }];
        
        [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(label3.mas_left).offset(-5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(30);
        }];
        
        return view;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 230.0, 24.0)];
        [view setBackgroundColor:SUMRIDGECOLOR];
        UILabel *label1 = [[UILabel alloc] init];
        label1.textColor = [UIColor whiteColor];
        label1.font = ARIAL10;
        label1.text = @"DELAYED TRACE";
        [view addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc] init];
        label2.textColor = [UIColor whiteColor];
        label2.textAlignment = NSTextAlignmentRight;
        label2.font = ARIAL10;
        label2.text = @"Yield";
        [view addSubview:label2];
        
        UILabel *label3 = [[UILabel alloc] init];
        label3.textColor = [UIColor whiteColor];
        label3.textAlignment = NSTextAlignmentRight;
        label3.font = ARIAL10;
        label3.text = @"Spread";
        [view addSubview:label3];
        
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(160);
        }];
        
        [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).offset(-5);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(40);
        }];
        
        [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(label3.mas_left).offset(-20);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(30);
        }];
        
        return view;
    }
}

#pragma mark - Scroll view delegate

@end
